package com.android.bookgarden.ui;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.bookgarden.MyApplication;
import com.android.bookgarden.R;
import com.android.bookgarden.apis.Apis;
import com.android.bookgarden.base.BaseActivity;
import com.android.bookgarden.bean.DataBean;
import com.android.bookgarden.bean.UserInfo;
import com.android.bookgarden.constract.RealtConstract;
import com.android.bookgarden.network.HttpType;
import com.android.bookgarden.persenter.BasePersenter;
import com.android.bookgarden.utli.JsonUitl;
import com.android.bookgarden.utli.LogUtil;
import com.android.bookgarden.utli.SpUtils;
import com.android.bookgarden.utli.Utlis;
import com.android.bookgarden.utli.otherlogin.QQLogin;
import com.android.bookgarden.views.LoadingDialog;
import com.android.bookgarden.wxapi.WXEntryActivity;
import com.tencent.connect.common.Constants;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.Tencent;


import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;

/**
 * Create by zouqh
 * on 2018/11/28
 **/
public class LoginActivity extends BaseActivity implements View.OnClickListener, com.android.bookgarden.utli.otherlogin.QQLogin.QqCallback, RealtConstract.View {
    @BindView(R.id.close)
    ImageView close;
    @BindView(R.id.title_text)
    TextView titleText;
    @BindView(R.id.ritgh_icon)
    ImageView ritghIcon;
    @BindView(R.id.ritgh_text)
    TextView ritghText;
    @BindView(R.id.telPhone)
    EditText telPhone;
    @BindView(R.id.passWord)
    EditText passWord;
    @BindView(R.id.lookPass)
    CheckBox lookPass;
    @BindView(R.id.userXy)
    TextView userXy;
    @BindView(R.id.loinBut)
    TextView loinBut;
    @BindView(R.id.phoneLogin)
    TextView phoneLogin;
    @BindView(R.id.goRegister)
    TextView goRegister;
    @BindView(R.id.QQLogin)
    TextView QQLogin;
    @BindView(R.id.WeixinLogin)
    TextView WeixinLogin;
    @BindView(R.id.fundPass)
    TextView fundPass;

    private QQLogin qqLogin;
    private QQLogin.BaseUiListener baseUiListener;

    private RealtConstract.Presenter presenter;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close:
                finish();
                break;
            case R.id.phoneLogin:
                finish();
                startActivity(TelLoginActivity.class);
                break;
            case R.id.goRegister:
                startActivity(RegisterActivity.class);
                break;
            case R.id.fundPass:
                startActivity(FundPassWordActivity.class);
                break;
            case R.id.QQLogin:
                qqLogin.setmTencent();
                break;

            case R.id.WeixinLogin:
                loginToWeiXin();
                break;

            case R.id.loinBut:
                login();
                break;

            case R.id.userXy:
                Intent intent = new Intent(this,HtmlActivity.class);
                intent.putExtra("type","1");
                startActivity(intent);
                break;

        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.actiity_login;
    }

    @Override
    protected void initView() {
        close.setOnClickListener(this);
        goRegister.setOnClickListener(this);
        loinBut.setOnClickListener(this);
        QQLogin.setOnClickListener(this);
        WeixinLogin.setOnClickListener(this);
        phoneLogin.setOnClickListener(this);
        fundPass.setOnClickListener(this);
        userXy.setOnClickListener(this);
        qqLogin = new QQLogin(this,this);
        presenter =new  BasePersenter(this,this);
        lookPass.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                // TODO Auto-generated method stub
                if (isChecked) {
                    // 设置成明文
                    // This transformation method causes any carriage return

                    passWord
                            .setTransformationMethod(HideReturnsTransformationMethod
                                    .getInstance());
                } else {
                    // 设置成密文
                    //
                    passWord
                            .setTransformationMethod(PasswordTransformationMethod
                                    .getInstance());
                }
            }
        });
    }

    @Override
    public void onRequestPermissions(String str, boolean z) {

    }

    private void login() {
        String name = telPhone.getText().toString();
        String password = passWord.getText().toString();
        if (TextUtils.isEmpty(name) || name.length() != 11) {
            showToast("请输入正确的手机号码");
            return;
        }

        if (TextUtils.isEmpty(password) || password.length() < 6) {
            showToast("请输入6-16位的密码");
            return;
        }

        String pass = Utlis.getMD5(password);
        pass = Utlis.getMD5(pass);

        LoadingDialog.showMassge(this,"登录中...");
        Map<String,String> map = new HashMap<>();
        map.put("name",name);
        map.put("password",pass);
        presenter.loadData(map,"", Apis.USER_LOGIN,1001);


    }


    @Override
    public void getUILister(QQLogin.BaseUiListener base) {
        this.baseUiListener = base;
    }

    @Override
    public void getQQInfo(String json) {
        LogUtil.d("json",json);
    }


    /**
     * 在调用Login的Activity或者Fragment中重写onActivityResult方法
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.REQUEST_LOGIN) {
            Tencent.onActivityResultData(requestCode, resultCode, data, baseUiListener);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    private void loginToWeiXin(){
        IWXAPI mApi = WXAPIFactory.createWXAPI(this, WXEntryActivity.WEIXIN_APP_ID, true);
        mApi.registerApp(WXEntryActivity.WEIXIN_APP_ID);

        if (mApi != null && mApi.isWXAppInstalled()) {
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "wechat_sdk_demo_test_neng";
            mApi.sendReq(req);
        } else
            Toast.makeText(this, "用户未安装微信", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void returnData(String data, int urlCode) {


        if (TextUtils.isEmpty(data))
        {
            return;
        }
        handler.obtainMessage(urlCode,data).sendToTarget();
    }

    @Override
    public void LoadError(String errorMsg, int urlCode) {
        showToast("登录请求失败");
        LoadingDialog.hideProgress();
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String str = (String) msg.obj;
            switch (msg.what){
                case 1001:

                    if (TextUtils.isEmpty(str)){
                        LoadingDialog.hideProgress();
                        return;
                    }

                    DataBean bean = Utlis.getDataBean(str);
                    showToast(bean.getMessage());
                    if (bean.getCode()==200){
                        try {
                            JSONObject object = new JSONObject(bean.getData());

                            SpUtils.getInstance().save(LoginActivity.this,"token",""+object.getString("token"));
                            String pass = Utlis.getMD5(passWord.getText().toString());
                            pass = Utlis.getMD5(pass);
                            SpUtils.getInstance().save(LoginActivity.this,"password",""+pass);

                            presenter.loadDataHeader(null,"",Apis.GET_USERINFO,1002,Utlis.getHeadler(LoginActivity.this), HttpType.GET);
                        } catch (JSONException e) {
                            e.printStackTrace();
                            LoadingDialog.hideProgress();
                        }

                    }else{
                        LoadingDialog.hideProgress();
                    }
                    break;

                case 1002:
                    LoadingDialog.hideProgress();
                    bean = Utlis.getDataBean(str);
                    if (bean.getCode()==200){

                            MyApplication.getInstance().userInfo = (UserInfo) JsonUitl.stringToObject(bean.getData(), UserInfo.class);
                            SpUtils.getInstance().save(LoginActivity.this,"userinfo",""+bean.getData());

                        finish();

                    }
                    break;
            }

        }
    };
}
